import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_module/beans/conmmonResult.dart';
import 'package:flutter_module/config/api.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_module/http/api_service.dart';
import 'package:flutter_module/util/theme_util.dart';
import 'package:oktoast/oktoast.dart';

import '../../DemoLocalizations.dart';

class repassword extends StatefulWidget {
  repassword({Key key}) : super(key: key);

  @override
  _repassword createState() => new _repassword();
}

class _repassword extends State<repassword> {
  bool sendCodeBtn = true;
  int seconds = 10;
  bool isButtonEnable = true; //按钮状态 是否可点击
  String buttonText = '发送验证码'; //初始文本

  Color themeColor = ThemeUtils.currentColorTheme;

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  final FocusNode myFocusNodeEmailLogin = FocusNode();
  final FocusNode myFocusNodePasswordLogin = FocusNode();

  final FocusNode myFocusNodePassword = FocusNode();
  final FocusNode myFocusNodeName = FocusNode();
  final FocusNode myFocusNodePhone = FocusNode();

  TextEditingController loginEmailController = new TextEditingController();
  TextEditingController loginPasswordController = new TextEditingController();

  bool _obscureTextSignup = true;
  bool _obscureTextSignupConfirm = true;

  TextEditingController signupPhoneController = new TextEditingController();
  TextEditingController signupSMScodeController = new TextEditingController();

  TextEditingController signupNameController = new TextEditingController();
  TextEditingController signupPasswordController = new TextEditingController();
  TextEditingController signupConfirmPasswordController =
      new TextEditingController();

  PageController _pageController;

  Color left = Colors.black;
  Color right = Colors.white;

  String title = "修改密码";
  Timer t;

  @override
  Widget build(BuildContext context) {
    buttonText = DemoLocalizations.of(context).SendVerification;
    title = DemoLocalizations.of(context).changePassword;
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        centerTitle: true,
      ),
      body: NotificationListener<OverscrollIndicatorNotification>(
        onNotification: (overscroll) {
          overscroll.disallowGlow();
        },
        child: SingleChildScrollView(
            child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height >= 775.0
              ? MediaQuery.of(context).size.height
              : 775.0,
          decoration: new BoxDecoration(
            gradient: new LinearGradient(
                colors: [Color(0xFFffffff), Color(0xFFffffff)],
                begin: const FractionalOffset(0.0, 0.0),
                end: const FractionalOffset(1.0, 1.0),
                stops: [0.0, 1.0],
                tileMode: TileMode.clamp),
          ),
          child: Column(
            children: <Widget>[
              Container(
                height: 20.0,
                child: Padding(
                  padding: EdgeInsets.only(top: 60.0),
                ),
              ),
              Expanded(
                // 在ListView上在包裹一层Flexible
                child: new ConstrainedBox(
                  constraints: const BoxConstraints.expand(),
                  child: _buildSignUp(context),
                ),
              )
            ],
          ),
        )),
      ),
    );
  }

  @override
  void dispose() {
    myFocusNodePassword.dispose();
    myFocusNodeName.dispose();
    _pageController?.dispose();
    if (t != null) {
      t.cancel();
    }
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
  }

  Widget _buildSignUp(BuildContext context) {
    //倒计时
    _showTimer() {
//      print("执行倒计时");
      t = Timer.periodic(Duration(milliseconds: 1000), (timer) {
        setState(() {
          this.seconds--;
        });
        if (this.seconds == 0) {
          if (t != null) {
            t.cancel();
          } //清除定时器：
          setState(() {
            this.sendCodeBtn = true;
          });
        }
      });
    }

    //重新发送验证码：
    sendCode() async {
      if (!sendCodeBtn) {
        return;
      }
      String mobile = signupPhoneController.text;
      if (mobile.trim().length < 6) {
        showToast("请输入正确的手机号！");
        return;
      }
      String smsmode = API.SMS_TPL_TYPE_2;
      ApiService().sendPhoneSMS((Response response) {
        if (response != null) {
          ConmmonResult conmmonResult = ConmmonResult.fromJson(response.data);
          if (conmmonResult.success) {
            showToast(conmmonResult.message);
            setState(() {
              this.sendCodeBtn = false;
              this.seconds = 60;
              _showTimer();
            });
          } else {
            showToast(conmmonResult.message);
            if (t != null) {
              t.cancel();
            } //清除定时器：
            setState(() {
              this.seconds == 0;
              this.isButtonEnable = true;
            });
          }
        }
      }, mobile, smsmode);
    }

    Future<Null> _regist() async {
      String password = signupPasswordController.text;
      String rePassword = signupConfirmPasswordController.text;

      String mobile = signupPhoneController.text;
      String smsmode = signupSMScodeController.text;

      if ((null != mobile && mobile.trim().length > 0) &&
          (null != smsmode && smsmode.trim().length == 6) &&
          (null != password && password.trim().length > 0) &&
          (null != rePassword && rePassword.trim().length > 0)) {
        if (smsmode.trim().length != 6) {
          showToast(DemoLocalizations.of(context).enterCorrect);
        }
        if (password != rePassword) {
          showToast(DemoLocalizations.of(context).passwordInconsistent);
        } else {
          ApiService().repassword((Response response) {
            if (response != null) {
              ConmmonResult conmmonResult =
                  ConmmonResult.fromJson(response.data);
              if (conmmonResult.success) {
                showToast(conmmonResult.message);
              } else {
                showToast(conmmonResult.message);
              }
            }
          }, mobile, password, smsmode);
        }
      } else {
        showToast(DemoLocalizations.of(context).cannotBeEmpty);
      }
    }

    return Container(
      padding: EdgeInsets.only(top: 23.0),
      child: Column(
        children: <Widget>[
          Stack(
            alignment: Alignment.topCenter,
            overflow: Overflow.visible,
            children: <Widget>[
              Card(
                elevation: 2.0,
                color: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: Container(
                  width: MediaQuery.of(context).size.width < 340.0
                      ? MediaQuery.of(context).size.width
                      : 340.0,
                  height: 410.0,
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(
                            top: 10.0, bottom: 10.0, left: 25.0, right: 25.0),
                        child: TextField(
                          focusNode: myFocusNodePhone,
                          controller: signupPhoneController,
                          keyboardType: TextInputType.number,
                          textCapitalization: TextCapitalization.words,
                          style: TextStyle(fontSize: 16.0, color: Colors.black),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            icon: Icon(
                              FontAwesomeIcons.user,
                              color: Colors.black,
                            ),
                            hintText: DemoLocalizations.of(context).phoneNumber,
                            hintStyle: TextStyle(fontSize: 16.0),
                          ),
                        ),
                      ),
                      Container(
                        width: 250.0,
                        height: 1.0,
                        color: Colors.grey[400],
                      ),
                      Container(
                        color: Colors.white,
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(left: 50, right: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
    crossAxisAlignment: CrossAxisAlignment.center,
                          // crossAxisAlignment: CrossAxisAlignment.baseline,
                          textBaseline: TextBaseline.ideographic,
                          children: <Widget>[
//                            Text('验证码',style: TextStyle(fontSize: 13,color: Color(0xff333333)),),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.only(
                                    left: 15, right: 15, top: 0),
                                child: TextFormField(
                                  maxLines: 1,
                                  onSaved: (value) {},
                                  controller: signupSMScodeController,
                                  textAlign: TextAlign.left,
                                  inputFormatters: [
                                    WhitelistingTextInputFormatter.digitsOnly,
                                    LengthLimitingTextInputFormatter(6)
                                  ],
                                  decoration: InputDecoration(
                                    hintText: (DemoLocalizations.of(context)
                                        .Fillverification),
                                    contentPadding:
                                        EdgeInsets.only(top: -5, bottom: 0),
                                    hintStyle: TextStyle(
                                      // color: Color(0xff999999),
                                      color: Colors.grey[300],
                                      fontSize: 14,
                                    ),
                                    alignLabelWithHint: true,
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide.none),
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              width: 120,
                              alignment: Alignment.center,
                              padding:
                                  const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 6.0),
                              child: FlatButton(
                                disabledColor:
                                    Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                                disabledTextColor: Colors.white, //按钮禁用时的文本颜色
                                textColor: sendCodeBtn
                                    ? Colors.white
                                    : Colors.black.withOpacity(0.2), //文本颜色
                                color: sendCodeBtn
                                    ? Color(0xff44c5fe)
                                    : Colors.grey.withOpacity(0.1), //按钮的颜色
                                splashColor: sendCodeBtn
                                    ? Colors.white.withOpacity(0.1)
                                    : Colors.transparent,
                                shape: StadiumBorder(side: BorderSide.none),
                                onPressed: () {
                                  setState(() {
                                    sendCode();
                                  });
                                },
                                //      child: Text('重新发送 (${secondSy})'),
                                child: Text(
                                  '$buttonText',
                                  style: TextStyle(
                                      // fontSize: 13,
                                      ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: 250.0,
                        height: 1.0,
                        color: Colors.grey[400],
                      ),
//                      Padding(
//                        padding: EdgeInsets.only(
//                            top: 10.0, bottom: 10.0, left: 25.0, right: 25.0),
//                        child: TextField(
//                          focusNode: myFocusNodeName,
//                          controller: signupNameController,
//                          keyboardType: TextInputType.text,
//                          textCapitalization: TextCapitalization.words,
//                          style: TextStyle(fontSize: 16.0, color: Colors.black),
//                          decoration: InputDecoration(
//                            border: InputBorder.none,
//                            icon: Icon(
//                              FontAwesomeIcons.user,
//                              color: Colors.black,
//                            ),
//                            hintText: "用户名",
//                            hintStyle: TextStyle(fontSize: 16.0),
//                          ),
//                        ),
//                      ),
//                      Container(
//                        width: 250.0,
//                        height: 1.0,
//                        color: Colors.grey[400],
//                      ),
                      Padding(
                        padding: EdgeInsets.only(
                            top: 10.0, bottom: 10.0, left: 25.0, right: 25.0),
                        child: TextField(
                          focusNode: myFocusNodePassword,
                          controller: signupPasswordController,
                          obscureText: _obscureTextSignup,
                          style: TextStyle(fontSize: 16.0, color: Colors.black),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            icon: Icon(
                              FontAwesomeIcons.lock,
                              color: Colors.black,
                            ),
                            hintText: DemoLocalizations.of(context).NewPassword,
                            hintStyle: TextStyle(fontSize: 16.0),
                            suffixIcon: GestureDetector(
                              onTap: _toggleSignup,
                              child: Icon(
                                FontAwesomeIcons.eye,
                                size: 15.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        width: 250.0,
                        height: 1.0,
                        color: Colors.grey[400],
                      ),
                      Padding(
                        padding: EdgeInsets.only(
                            top: 10.0, bottom: 10, left: 25.0, right: 25.0),
                        child: TextField(
                          controller: signupConfirmPasswordController,
                          obscureText: _obscureTextSignupConfirm,
                          style: TextStyle(fontSize: 16.0, color: Colors.black),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            icon: Icon(
                              FontAwesomeIcons.lock,
                              color: Colors.black,
                            ),
                            hintText:
                                DemoLocalizations.of(context).confirmPassword,
                            hintStyle: TextStyle(fontSize: 16.0),
                            suffixIcon: GestureDetector(
                              onTap: _toggleSignupConfirm,
                              child: Icon(
                                FontAwesomeIcons.eye,
                                size: 15.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 340.0),
                decoration: new BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                ),
                child: FlatButton(
                    shape: RoundedRectangleBorder(
                        side: BorderSide(
                          color: themeColor,
                          width: 1,
                        ),
                        borderRadius: BorderRadius.circular(30)),
                    color: themeColor,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                          vertical: 10.0, horizontal: 60.0),
                      child: Text(
                        DemoLocalizations.of(context).Submit,
                        style: TextStyle(color: Colors.white, fontSize: 18.0),
                      ),
                    ),
                    onPressed: () {
                      _regist();
                    }),
              ),
            ],
          ),
        ],
      ),
    );
  }

  //注册密码安全开关
  void _toggleSignup() {
    setState(() {
      _obscureTextSignup = !_obscureTextSignup;
    });
  }

  //注册确认密码安全开关
  void _toggleSignupConfirm() {
    setState(() {
      _obscureTextSignupConfirm = !_obscureTextSignupConfirm;
    });
  }
}
